<?php
/**
 * 登录操作类
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2018/7/20
 * Time: 15:45
 */
namespace app\admin\controller;

class Login extends Base{
    protected function _initialize(){
        $this->needLogin = false;  // 关闭登录验证
        $this->needAuth  = false;  // 关闭权限验证
        $this->needCheck = false;  // 关闭状态验证
        parent::_initialize();
    }

    /**
     * 登录
     * @return string|\think\response\Json|\think\response\View
     */
    public function login(){
        if (IS_POST) {
            try{
                // 场景验证
                $validate = $this->validate($this->params,'Login.login');
                if( true !== $validate ) throw new \Exception($validate, -1);

                $info = $this->getRow($this->admin, ['username'=>$this->params['username'],'status'=>\Param::STATUS_ON], 'id,password,portrait');
                if ( !$info ) throw new \Exception('用户不存在或已禁用!', -1);
                if ( !password_verify($this->params['password'], $info['password']) ) throw new \Exception('密码错误', -1);

                self::_afterLogin($info);  // 登录后置操作

                $this->logs[] = ['登录', \Param::LOG_TYPE_LOGIN, '登录成功'];
            } catch (\Exception $e){
                return _error($e->getCode(),$e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return _success();
        }
        $portrait = cookie('portrait') ?: '/static/admin/picture/avatar.png';
        return view('login', ['portrait'=>$portrait]);
    }

    /**
     * 登出
     */
    public function logout(){
        \think\Session::delete('login');
        self::redirect('login/login');
    }

    /**
     * 登录后置操作
     * @param $info
     */
    protected function _afterLogin($info){
        // 更新用户登陆信息
        $save['id']               = $info['id'];
        $save['last_login_time']  = time();
        $save['last_login_ip']    = getIpLong();
        $this->admin->update($save);

        $expire = empty($this->params['remember']) ? 3600 : 3600 * 24;
        \think\Session::init([
            'prefix'     => 'tp5.login',
            'expire'     => $expire,
            'path'       => TEMP_PATH,  //和其他运行在同一个服务器的session进行隔离，避免相互干扰
            'auto_start' => true,
        ]);
        \think\Session::set('login', $info['id']);
        \think\Session::set('session.end_time', time()+$expire);

        cookie('portrait', null);  // 记录头像
        cookie('portrait', $info['portrait']);
    }
}